package me.zhengjie.modules.utils;

import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.core.auth.Auth;
import com.baidubce.qianfan.model.chat.ChatResponse;
import com.google.gson.Gson;

import java.util.Iterator;
import java.util.concurrent.atomic.AtomicReference;

public class ChatUtils {
    Qianfan qianfan = new Qianfan(Auth.TYPE_OAUTH, "IBJfsotAa3kBp6SbTP4bI2Pv", "MmYjJOvnfM9vXQ8yIMNhYYxLlvNgeE0I");

    private ChatUtils() {
    }

    private static class ChatUtilsHolder {
        private static final ChatUtils INSTANCE = new ChatUtils();
    }

    public static final ChatUtils getInstance() {
        return ChatUtilsHolder.INSTANCE;
    }

    public String getReplay(String question) {
        ChatResponse response = qianfan.chatCompletion()
                .model("ERNIE-Bot-4")
                .addMessage("user", question)
                .temperature(0.7)
                .execute();
        return response.getResult();
    }
    public String getStreamReplay(String question) {
        StringBuilder reply = new StringBuilder();
        Iterator<ChatResponse> iterator = qianfan.chatCompletion()
                .addMessage("user", question)
                .executeStream();
        while (iterator.hasNext()) {
            ChatResponse next = iterator.next();
            reply.append(next.getResult());
        }
        return reply.toString();
    }

    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        Qianfan qianfan = new Qianfan(Auth.TYPE_OAUTH, "IBJfsotAa3kBp6SbTP4bI2Pv", "MmYjJOvnfM9vXQ8yIMNhYYxLlvNgeE0I");
        /*ChatResponse response = qianfan.chatCompletion()
                .model("ERNIE-Bot-4") // 使用model指定预置模型
                 //.endpoint("completions_pro") // 也可以使用endpoint指定任意模型 (二选一)
                 //.endpoint("eb-instant") // 也可以使用endpoint指定任意模型 (二选一)
                .addMessage("user", "你叫什么名字") // 添加用户消息 (此方法可以调用多次，以实现多轮对话的消息传递)
                //.temperature(0.8) // 自定义超参数
                .execute(); // 发起请求
        System.out.println(response.getResult());
        System.out.println(System.currentTimeMillis()-start);*/

        StringBuilder reply = new StringBuilder();
        Iterator<ChatResponse> iterator = qianfan.chatCompletion()
                .model("ERNIE-Bot-4")
                .addMessage("user", "atmr 心智")
                // 设置温度
                .temperature(0.7)
                // 设置top_p
                .topP(0.9)
                .executeStream();
        while (iterator.hasNext()) {
            ChatResponse next = iterator.next();
            reply.append(next.getResult());
            System.out.println(next.getId());
        }
        System.out.println("========================");
        System.out.println(reply);
        System.out.println(System.currentTimeMillis() - start);
    }
}
